import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:string_validator/string_validator.dart';

import '../../common/config.dart';
import '../../common/utils/app.dart';
import '../../common/utils/crypto.dart';
import '../../common/utils/simulator.dart';

final strategy = Strategy._();

class Strategy {
  Strategy._();

  final String host = SDK.kStrategyHost;

  late final Dio dio = Dio(BaseOptions(
    contentType: 'text/html',
    baseUrl: 'https://$host',
    connectTimeout: const Duration(seconds: 10),
    sendTimeout: const Duration(seconds: 10),
    receiveTimeout: const Duration(seconds: 10),
  ));

  Future<List<String>> getStrategy() async {
    final List<String> urls = [];
    try {
      bool prevent = await checkIfPrevent();
      if (prevent) {
        return urls;
      }

      PackageInfo info = await appInfo();
      String packageName = info.packageName;
      String version = info.version;
      bool simExists = await checkSimExists();

      // package,version,sim,encrypt
      // str,str,bool,bool
      final String text = '$packageName,$version,$simExists,true';
      final String key = host.replaceAll('.', '');
      final String data = xorEncrypt(text, key);
      Response<String>? result;
      result = await dio.post('/', data: data);
      if (result.statusCode == HttpStatus.ok) {
        String source = result.data!;
        if (!isJson(source)) {
          source = xorDecrypt(source, key);
        }
        if(source.isNotEmpty) {
          List<dynamic> datas = jsonDecode(source);
          urls.addAll(datas.map((e) => e.toString()));
        }
      }
    } catch(e) {}
    return urls;
  }
}
